import { useState, useEffect, useCallback, Fragment } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import {
  PageHeader,
  Steps,
  Button,
  Space,
  Form,
  Input,
  Select,
  message
} from 'antd';
import { ProfileOutlined, MessageOutlined, CloudUploadOutlined } from '@ant-design/icons';
import NewsEditor from '@/components/News-manage/NewsEditor';
import style from './News.module.scss'
import { http } from '@/utils/http'
const { Step } = Steps;
const { Option } = Select;

export default function NewsUpdate() {
  const { id } = useParams()
  const navigate = useNavigate()
  const [newsInfo, setNewsInfo] = useState([])  // 要更新的文章的数据列表
  const [current, setCurrent] = useState(0)  // 当前步骤
  const [newsCategories, setNewsCategories] = useState([])  // 新闻分类列表
  const [formInfo, setFormInfo] = useState({})  // 表单信息
  const [content, setContent] = useState("")  // 内容信息

  const [form] = Form.useForm()

  // 获取当前需要更新的文章信息
  const getNewsInfo = useCallback(async () => {
    const { data } = await http.get(`/news?id=${id}&_expand=category&_expand=role`)
    form.setFieldsValue({
      title: data[0].title,
      categoryId: data[0].categoryId
    })
    setNewsInfo(data[0])
    setContent(data[0].content)
    console.log(data[0])
  }, [id, form])

  // 获取新闻分类列表
  const getNewsCategories = async () => {
    const { data } = await http.get('/categories')
    setNewsCategories(data)
  }

  useEffect(() => {
    getNewsCategories()
    getNewsInfo()
  }, [getNewsInfo])

  // 下一步的回调
  const handleNext = () => {
    if (current === 0) {
      form.validateFields()
        .then(res => {
          setFormInfo(res)
          setCurrent(current + 1)
        })
        .catch(() => {
          message.info('请检查表单项！', 2)
        })
    } else {
      if (content === "" || content === "<p></p>\n") {
        message.error('请输入正确的新闻内容！', 2)
      } else {
        setCurrent(current + 1)
      }
    }
  }

  // 点击保存草稿   /  提交审核
  const handleSave = auditState => {
    http.patch(`/news/${id}`, {
      ...formInfo,
      "content": content,
      "auditState": auditState,  // auditState 0草稿箱  1待审核  2审核通过  3审核不通过
    })
      .then(() => {
        message.success(auditState === 0 ? '保存到草稿箱成功！' : '提交审核成功！', 2)
        if (auditState === 0) navigate('/news-manage/draft')
        else navigate('/audit-manage/list')
      })
      .catch(() => {
        message.error(auditState === 0 ? '保存到草稿箱失败！' : '提交审核失败！', 2)
        setTimeout(() => {
          navigate(0)
        }, 1000)
      })
  }

  return (
    <Fragment>
      <PageHeader
        className="site-page-header"
        onBack={() => window.history.back()}
        title="更新新闻"
      />
      <Steps current={current}>
        <Step title="基本信息" description="新闻标题，新闻分类" icon={<ProfileOutlined />} />
        <Step title="新闻内容" description="新闻主体内容" icon={<MessageOutlined />} />
        <Step title="新闻提交" description="保存草稿或提交审核" icon={<CloudUploadOutlined />} />
      </Steps>

      <div style={{ marginTop: "50px" }}>
        {/* 步骤1 显示区域 */}
        <div className={current === 0 ? '' : style.hidden}>
          <Form
            form={form}
            name="basic"
            labelCol={{
              span: 2
            }}
            wrapperCol={{
              span: 22
            }}
            autoComplete="off"
            initialValues={{
              title: newsInfo?.title
            }}
          >
            <Form.Item
              label="新闻标题"
              name="title"
              rules={[
                {
                  required: true,
                  message: '请输入新闻标题！',
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="新闻分类"
              name="categoryId"
              rules={[
                {
                  required: true,
                  message: '请选择新闻分类！',
                },
              ]}
            >
              <Select
                style={{
                  width: '100%',
                }}
              >
                {
                  newsCategories.map(item => {
                    return <Option key={item.id} value={item.id}>{item.title}</Option>
                  })
                }
              </Select>
            </Form.Item>
          </Form>
        </div>

        {/* 步骤2 显示区域 */}
        <div className={current === 1 ? '' : style.hidden}>
          <NewsEditor getContent={value => setContent(value)} content={content} />
        </div>

        {/* 步骤3 显示区域 */}
        <div className={current === 2 ? '' : style.hidden}>
        </div>
      </div>

      {/* 按钮区域 */}
      <div style={{ margin: "40px 0" }}>
        <Space>
          {
            current === 2 && (
              <>
                <Button type='primary' onClick={() => handleSave(0)}>保存到草稿箱</Button>
                <Button danger onClick={() => handleSave(1)}>提交审核</Button>
              </>
            )
          }
          {
            current < 2 && (
              <Button type='primary' onClick={() => handleNext()}>下一步</Button>
            )
          }
          {
            current === 0 || (
              <Button onClick={() => setCurrent(current - 1)}>上一步</Button>
            )
          }
        </Space>
      </div>
    </Fragment>
  )
}